package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.IFSFunctionIds;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.coupon.vo.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.coupon.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.coupon.CouponBizService;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.platform.ltb.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.ltb.middle.entity.*;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cloudbroker.bcs.common.constants.BasicErrorCodes.*;
import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.CouponErrorInfo.*;
import static com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl.Common.*;
import static java.lang.Math.abs;

/*
 * 模块名称：优惠券接口
 * by xuss13891
 */

@Service
public class CouponBizServiceImpl implements CouponBizService {

	@Autowired
	private SqlSessionFactory sqlSessionFactory;

	@Autowired
	public CouponBizServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("development", transactionFactory, this.sqlSessionFactory.getConfiguration().getEnvironment().getDataSource());
		this.sqlSessionFactory.getConfiguration().setEnvironment(environment);
	}

	// 库存优惠券增加
	public CouponStockAddBack couponStockAdd(CouponStockAddVO couponStockAddVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			if (couponStockAddVO.getCoupon_stock_status() != 0 && couponStockAddVO.getCoupon_stock_status() != 1){
				return VOUtil.genErrorResult(PARAM_ERROR, "新增库存优惠券时coupon_stock_status只能为0（发布）或者1（保存）", CouponStockAddBack.class);
			}

			CouponStock record = new CouponStock();
			record.setMycat_flag(ConfigValues.getMycatFlag());
			//record.setCouponSid(couponStockAddVO.getCoupon_sid());
			record.setCompanyId(nullToEmpty(couponStockAddVO.getCompany_id()));
			record.setBusinessId(nullToEmpty(couponStockAddVO.getBusiness_id()));

			String couponCode = "";
			// 通用码则生成一个
			if (couponStockAddVO.getCoupon_code_type() == 1){
				do{
					couponCode = generateRandomString(16);
					record.setCouponCode(couponCode);
				}while ((int)conn.selectOne(MAPPER_PATH + "CouponUserMapper.testCouponCode", record) > 0);
			} else {
				record.setCouponCode(couponCode);
			}

			record.setCouponDescription(nullToEmpty(couponStockAddVO.getCoupon_description()));
			record.setCouponName(nullToEmpty(couponStockAddVO.getCoupon_name()));
			record.setCouponStockStatus(nullToEmpty(couponStockAddVO.getCoupon_stock_status()));
			record.setCouponType(nullToEmpty(couponStockAddVO.getCoupon_type()));
			if (couponStockAddVO.getCoupon_stock_status() != null && couponStockAddVO.getCoupon_stock_status() == 0){
				record.setCreateTime(System.currentTimeMillis());
			} else {
				record.setCreateTime((long)0);
			}
			record.setDeleteTime(new Long(0));
			record.setDiscountAmount(nullToEmpty(couponStockAddVO.getDiscount_amount()));
			record.setDiscountLimit(nullToEmpty(couponStockAddVO.getDiscount_limit()));
			record.setDiscountRate(nullToEmpty(couponStockAddVO.getDiscount_rate()));
			record.setDuration(nullToEmpty(couponStockAddVO.getDuration()));
			record.setGiveAmount(0);
			record.setUseAmount(0);
			record.setTotalAmount(nullToEmpty(couponStockAddVO.getTotal_amount()));
			record.setLimitAmount(nullToEmpty(couponStockAddVO.getLimit_amount()));
			record.setGiveBeginDate(nullToEmpty(couponStockAddVO.getGive_begin_date()));
			record.setGiveEndDate(nullToEmpty(couponStockAddVO.getGive_end_date()));
			record.setUseBeginDate(nullToEmpty(couponStockAddVO.getUse_begin_date()));
			record.setUseEndDate(nullToEmpty(couponStockAddVO.getUse_end_date()));
			record.setOperatorNo(nullToEmpty(couponStockAddVO.getOperator_no()));
			record.setOperatorName(nullToEmpty(couponStockAddVO.getOperator_name()));
			record.setRemark("");

			if (couponStockAddVO.getTarget_activities() != null && couponStockAddVO.getTarget_activities().size() > 0) {
				record.setLimitActivity((byte) 1);
			} else {
				record.setLimitActivity((byte) 0);
			}

			if (couponStockAddVO.getTarget_goods() != null && couponStockAddVO.getTarget_goods().size() > 0) {
				record.setLimitGoods((byte) 1);
			} else {
				record.setLimitGoods((byte) 0);
			}

			if (couponStockAddVO.getTarget_users() != null && couponStockAddVO.getTarget_users().size() > 0) {
				record.setLimitTarget((byte) 1);
			} else {
				record.setLimitTarget((byte) 0);
			}

			conn.insert(MAPPER_PATH + "CouponStockMapper.insert", record);
			Long lastInsertId = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectLastInsertId");

			if (couponStockAddVO.getTarget_activities() != null && couponStockAddVO.getTarget_activities().size() > 0){
				CouponActivity caRecord = new CouponActivity();
				caRecord.setCouponSid(lastInsertId);
				caRecord.setCompanyId(couponStockAddVO.getCompany_id());
				for(long activityId:couponStockAddVO.getTarget_activities()){
					caRecord.setActivityId(activityId);
					if (conn.selectOne(MAPPER_PATH + "CouponActivityMapper.selectByPrimaryKey", caRecord) == null){
						conn.insert(MAPPER_PATH + "CouponActivityMapper.insert", caRecord);
					}
				}
			}
			if (couponStockAddVO.getTarget_goods() != null && couponStockAddVO.getTarget_goods().size() > 0){
				CouponGoods cgRecord = new CouponGoods();
				cgRecord.setCouponSid(lastInsertId);
				cgRecord.setCompanyId(couponStockAddVO.getCompany_id());
				for(long goodsId:couponStockAddVO.getTarget_goods()){
					cgRecord.setGoodsId(goodsId);
					if (conn.selectOne(MAPPER_PATH + "CouponGoodsMapper.selectByPrimaryKey", cgRecord) == null){
						conn.insert(MAPPER_PATH + "CouponGoodsMapper.insert", cgRecord);
					}
				}
			}
			if (couponStockAddVO.getTarget_users() != null && couponStockAddVO.getTarget_users().size() > 0){
				CouponTarget ctRecord = new CouponTarget();
				ctRecord.setCouponSid(lastInsertId);
				ctRecord.setCompanyId(couponStockAddVO.getCompany_id());
				for(long userId:couponStockAddVO.getTarget_users()){
					ctRecord.setUserId(userId);
					if ((int)conn.selectOne(MAPPER_PATH + "CouponUserMapper.testUserId", ctRecord) <= 0){
						return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "user_id=" + userId + "不存在", CouponStockAddBack.class);
					}
					if (conn.selectOne(MAPPER_PATH + "CouponTargetMapper.selectByPrimaryKey", ctRecord) == null){
						conn.insert(MAPPER_PATH + "CouponTargetMapper.insert", ctRecord);
					}
				}
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(lastInsertId);
			couponJournal.setBusinessId(record.getBusinessId());
			couponJournal.setCompanyId(record.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_STOCK_ADD));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("库存优惠券新增:" + JSONObject.toJSON(couponStockAddVO).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			CouponStockAddBack back = new CouponStockAddBack();
			back.setCoupon_sid(lastInsertId);
			back.setCoupon_code(couponCode);

			conn.commit();
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponStockAddBack.class);
		}finally{
			conn.close();
		}
	}

	@Override
	public HSBCPSBackVO couponStockStop(CouponStockStopVO couponStockStopVO) {
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponStock record = new CouponStock();
			record.setCouponSid(couponStockStopVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if (stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponStockStopVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			if (stock.getCouponStockStatus() != 0){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "库存优惠券不是发布状态无法停用", HSBCPSBackVO.class);
			}
			record.setCouponStockStatus((byte)2);
			record.setDeleteTime(System.currentTimeMillis());
			record.setRemark("管理员[" + couponStockStopVO.getOperator_name() + "]于" + getCurrentDate() + "停止使用,停用原因:" + couponStockStopVO.getRemark());
			conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", record);

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_STOCK_STOP));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("库存优惠券停用:" + JSONObject.toJSON(couponStockStopVO).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 库存优惠券修改
	public HSBCPSBackVO couponStockMod(CouponStockModVO couponStockModVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponStock record = new CouponStock();
			record.setCouponSid(couponStockModVO.getCoupon_sid());
			CouponStock stock =conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if (stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponStockModVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			if (stock.getCouponStockStatus() != 1){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "库存优惠券不是保存状态无法修改", HSBCPSBackVO.class);
			}
			if (couponStockModVO.getCoupon_stock_status() != 0 && couponStockModVO.getCoupon_stock_status() != 1){
				return VOUtil.genErrorResult(PARAM_ERROR, "修改库存优惠券时coupon_stock_status只能为0（发布）或者1（保存）", HSBCPSBackVO.class);
			}
			record.setCouponStockStatus(couponStockModVO.getCoupon_stock_status());
			record.setTotalAmount(couponStockModVO.getTotal_amount());
			record.setLimitAmount(couponStockModVO.getLimit_amount());
			record.setDuration(couponStockModVO.getDuration());
			record.setGiveBeginDate(couponStockModVO.getGive_begin_date());
			record.setGiveEndDate(couponStockModVO.getGive_end_date());
			record.setUseBeginDate(couponStockModVO.getUse_begin_date());
			record.setUseEndDate(couponStockModVO.getUse_end_date());
			record.setCouponDescription(nullToEmpty(couponStockModVO.getCoupon_description()));
			record.setCouponName(nullToEmpty(couponStockModVO.getCoupon_name()));
			record.setCouponType(nullToEmpty(couponStockModVO.getCoupon_type()));
			if (couponStockModVO.getCoupon_stock_status() != null && couponStockModVO.getCoupon_stock_status() == 0){
				record.setCreateTime(System.currentTimeMillis());
			} else {
				record.setCreateTime((long)0);
			}
			record.setDiscountAmount(couponStockModVO.getDiscount_amount());
			record.setDiscountLimit(couponStockModVO.getDiscount_limit());
			record.setDiscountRate(couponStockModVO.getDiscount_rate());
			record.setBusinessId(couponStockModVO.getBusiness_id());


			if (couponStockModVO.getTarget_activities() != null){
				conn.delete(MAPPER_PATH + "CouponActivityMapper.deleteByCouponSid", record);
				if (couponStockModVO.getTarget_activities().isEmpty()){
					record.setLimitActivity((byte)0);
				} else {
					record.setLimitActivity((byte)1);
					CouponActivity caRecord = new CouponActivity();
					caRecord.setCouponSid(couponStockModVO.getCoupon_sid());
					caRecord.setCompanyId(stock.getCompanyId());
					for(long activityId:couponStockModVO.getTarget_activities()){
						caRecord.setActivityId(activityId);
						if (conn.selectOne(MAPPER_PATH + "CouponActivityMapper.selectByPrimaryKey", caRecord) == null){
							conn.insert(MAPPER_PATH + "CouponActivityMapper.insert", caRecord);
						}
					}
				}
			}
			if (couponStockModVO.getTarget_goods() != null){
				conn.delete(MAPPER_PATH + "CouponGoodsMapper.deleteByCouponSid", record);
				if (couponStockModVO.getTarget_goods().isEmpty()){
					record.setLimitGoods((byte)0);
				} else {
					record.setLimitGoods((byte) 1);
					CouponGoods cgRecord = new CouponGoods();
					cgRecord.setCouponSid(couponStockModVO.getCoupon_sid());
					cgRecord.setCompanyId(stock.getCompanyId());
					for (long goodsId : couponStockModVO.getTarget_goods()) {
						cgRecord.setGoodsId(goodsId);
						if (conn.selectOne(MAPPER_PATH + "CouponGoodsMapper.selectByPrimaryKey", cgRecord) == null) {
							conn.insert(MAPPER_PATH + "CouponGoodsMapper.insert", cgRecord);
						}
					}
				}
			}
			if (couponStockModVO.getTarget_users() != null){
				conn.delete(MAPPER_PATH + "CouponTargetMapper.deleteByCouponSid", record);
				if (couponStockModVO.getTarget_users().isEmpty()){
					record.setLimitTarget((byte)0);
				} else {
					record.setLimitTarget((byte) 1);
					CouponTarget ctRecord = new CouponTarget();
					ctRecord.setCouponSid(couponStockModVO.getCoupon_sid());
					ctRecord.setCompanyId(stock.getCompanyId());
					for (long userId : couponStockModVO.getTarget_users()) {
						ctRecord.setUserId(userId);
						if ((int)conn.selectOne(MAPPER_PATH + "CouponUserMapper.testUserId", ctRecord) <= 0){
							return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "user_id=" + userId + "不存在", HSBCPSBackVO.class);
						}
						if (conn.selectOne(MAPPER_PATH + "CouponTargetMapper.selectByPrimaryKey", ctRecord) == null) {
							conn.insert(MAPPER_PATH + "CouponTargetMapper.insert", ctRecord);
						}
					}
				}
			}
			conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", record);

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_STOCK_MOD));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("库存优惠券修改:" + JSONObject.toJSON(couponStockModVO).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 库存优惠券删除
	public HSBCPSBackVO couponStockDel(CouponStockDelVO couponStockDelVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponStock record = new CouponStock();
			record.setCouponSid(couponStockDelVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if (stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponStockDelVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			if (stock.getCouponStockStatus() != 0){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "库存优惠券[coupon_sid=" + couponStockDelVO.getCoupon_sid() + "]状态不正确无法删除", HSBCPSBackVO.class);
			}
			record.setCouponStockStatus((byte)4);
			record.setDeleteTime(System.currentTimeMillis());
			conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", record);

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_STOCK_DEL));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("库存优惠券删除:" + JSONObject.toJSON(couponStockDelVO).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 库存优惠券查询
	public CouponStockQryBack couponStockQry(CouponStockQryVO couponStockQryVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			// 查询前扫描过期的优惠券
			updateStockExpired(conn);

			Map mapIn = new HashMap<String, Object>();
			mapIn.put("couponSid", couponStockQryVO.getCoupon_sid());
			mapIn.put("couponType", couponStockQryVO.getCoupon_type());
			mapIn.put("businessId", couponStockQryVO.getBusiness_id());
			mapIn.put("companyId", couponStockQryVO.getCompany_id());
			mapIn.put("couponName", couponStockQryVO.getCoupon_name());
			mapIn.put("couponCode", couponStockQryVO.getCoupon_code());
			mapIn.put("goodsId", couponStockQryVO.getGoods_id());
			mapIn.put("pageNo", couponStockQryVO.getPage_no());
			mapIn.put("pageSize", couponStockQryVO.getPage_size());

			int count = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectCount", mapIn);
			List<CouponStockQryBean> retList = conn.selectList(MAPPER_PATH + "CouponStockMapper.selectByCondition", mapIn);
			for (CouponStockQryBean bean:retList){
				if (bean.getLimit_activity() == 1){
					CouponActivity record = new CouponActivity();
					record.setCouponSid(bean.getCoupon_sid());
					List<Long> list = conn.selectList(MAPPER_PATH + "CouponActivityMapper.selectIds", record);
					bean.setTarget_activities(list);
				}
				if (bean.getLimit_target() == 1){
					CouponTarget record = new CouponTarget();
					record.setCouponSid(bean.getCoupon_sid());
					List<Long> list = conn.selectList(MAPPER_PATH + "CouponTargetMapper.selectIds", record);
					bean.setTarget_users(list);
				}
				if (bean.getLimit_goods() == 1){
					CouponGoods record = new CouponGoods();
					record.setCouponSid(bean.getCoupon_sid());
					List<Long> list = conn.selectList(MAPPER_PATH + "CouponGoodsMapper.selectIds", record);
					bean.setTarget_goods(list);
				}
			}
			CouponStockQryBack back = new CouponStockQryBack();
			back.setCount(count);
			back.setData_list(retList);
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponStockQryBack.class);
		}finally{
			conn.close();
		}
	}

	// 活动与优惠券绑定
	public HSBCPSBackVO couponActivityBind(CouponActivityBindVO couponActivityBindVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponActivity record = new CouponActivity();
			record.setCouponSid(couponActivityBindVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if ( stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponActivityBindVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			record.setCompanyId(stock.getCompanyId());
			for(long activityId:couponActivityBindVO.getActivity_ids()){
				record.setActivityId(activityId);
				if (conn.selectOne(MAPPER_PATH + "CouponActivityMapper.selectByPrimaryKey", record) == null){
					conn.insert(MAPPER_PATH + "CouponActivityMapper.insert", record);
				}
			}
			if (!couponActivityBindVO.getActivity_ids().isEmpty() && stock.getLimitActivity() == (byte)0){
				CouponStock updateRecord = new CouponStock();
				updateRecord.setLimitActivity((byte)1);
				conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", updateRecord);
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_ACTIVITY_BIND));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("活动与优惠券绑定:" + JSONObject.toJSON(couponActivityBindVO.getActivity_ids()).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 活动与优惠券解绑
	public HSBCPSBackVO couponActivityUnbind(CouponActivityUnbindVO couponActivityUnbindVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponActivity record = new CouponActivity();
			record.setCouponSid(couponActivityUnbindVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if ( stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponActivityUnbindVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			record.setCompanyId(stock.getCompanyId());
			for(long activityId:couponActivityUnbindVO.getActivity_ids()){
				record.setActivityId(activityId);
				conn.delete(MAPPER_PATH + "CouponActivityMapper.deleteByPrimaryKey", record);
			}
			if ((int)conn.selectOne(MAPPER_PATH + "CouponGoodsMapper.testCouponSid", record) <= 0){
				CouponStock updateRecord = new CouponStock();
				updateRecord.setCouponSid(couponActivityUnbindVO.getCoupon_sid());
				updateRecord.setLimitActivity((byte)0);
				conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", updateRecord);
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_ACTIVITY_UNBIND));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("活动与优惠券解绑:" + JSONObject.toJSON(couponActivityUnbindVO.getActivity_ids()).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 商品与优惠券绑定
	public HSBCPSBackVO couponGoodsBind(CouponGoodsBindVO couponGoodsBindVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponGoods record = new CouponGoods();
			record.setCouponSid(couponGoodsBindVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if ( stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponGoodsBindVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			record.setCompanyId(stock.getCompanyId());
			for(long goodsId:couponGoodsBindVO.getGoods_ids()){
				record.setGoodsId(goodsId);
				if (conn.selectOne(MAPPER_PATH + "CouponGoodsMapper.selectByPrimaryKey", record) == null){
					conn.insert(MAPPER_PATH + "CouponGoodsMapper.insert", record);
				}
			}
			if (!couponGoodsBindVO.getGoods_ids().isEmpty() && stock.getLimitGoods() == (byte)0){
				CouponStock updateRecord = new CouponStock();
				updateRecord.setLimitGoods((byte)1);
				conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", updateRecord);
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_GOODS_BIND));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("商品与优惠券绑定:" + JSONObject.toJSON(couponGoodsBindVO.getGoods_ids()).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 商品与优惠券解绑
	public HSBCPSBackVO couponGoodsUnbind(CouponGoodsUnbindVO couponGoodsUnbindVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponGoods record = new CouponGoods();
			record.setCouponSid(couponGoodsUnbindVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", record);
			if ( stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponGoodsUnbindVO.getCoupon_sid() + "]不存在", HSBCPSBackVO.class);
			}
			record.setCompanyId(stock.getCompanyId());
			for(long goodsId:couponGoodsUnbindVO.getGoods_ids()){
				record.setGoodsId(goodsId);
				conn.delete(MAPPER_PATH + "CouponGoodsMapper.deleteByPrimaryKey", record);
			}
			if ((int)conn.selectOne(MAPPER_PATH + "CouponGoodsMapper.testCouponSid", record) <= 0){
				CouponStock updateRecord = new CouponStock();
				updateRecord.setCouponSid(couponGoodsUnbindVO.getCoupon_sid());
				updateRecord.setLimitGoods((byte)0);
				conn.update(MAPPER_PATH + "CouponStockMapper.updateByPrimaryKey", updateRecord);
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId("");
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_GOODS_UNBIND));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("商品与优惠券解绑:" + JSONObject.toJSON(couponGoodsUnbindVO.getGoods_ids()).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 优惠券活动发放
	public CouponActivityGiveBack couponActivityGive(CouponActivityGiveVO couponActivityGiveVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponActivity record = new CouponActivity();
			record.setActivityId(couponActivityGiveVO.getActivity_id());
			List<CouponActivity> retList = conn.selectList(MAPPER_PATH + "CouponActivityMapper.selectCondition", record);
			if (retList == null || retList.isEmpty()){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "此活动[activity_id=" + couponActivityGiveVO.getActivity_id() + "]未绑定任何优惠券", CouponActivityGiveBack.class);
			}
			/*if (retList.size() > 1) {
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "此活动[activity_id=" + couponActivityGiveVO.getActivity_id() + "]绑定多张优惠券", CouponActivityGiveBack.class);
			}*/
			List<Long> couponUids = new ArrayList<Long>();
			String company_id = "";
			boolean oneSucceed = false;
			String errorInfo = "";
			for (CouponActivity one: retList){
				CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", one);
				if (stock == null){
					if (!errorInfo.isEmpty()) errorInfo += ", ";
					errorInfo += "优惠券[coupon_sid=" + one.getCouponSid() +"]不存在";
					continue;
				}

				Map<String, Object> mapIn1 = new HashMap<String, Object>();
				mapIn1.put("userId", couponActivityGiveVO.getUser_id());
				if ((int)conn.selectOne(MAPPER_PATH + "CouponUserMapper.testUserId", mapIn1) <= 0){
					return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "user_id=" + couponActivityGiveVO.getUser_id() + "不存在", CouponActivityGiveBack.class);
				}

				if (stock.getCouponStockStatus() != 0) {
					if (!errorInfo.isEmpty()) errorInfo += ", ";
					errorInfo +=  "优惠券[coupon_sid=" + one.getCouponSid() + "]状态不正确无法发放";
					continue;
				}

				if (stock.getGiveAmount() >= stock.getTotalAmount()) {
					if (!errorInfo.isEmpty()) errorInfo += ", ";
					errorInfo +=  "优惠券[coupon_sid=" + one.getCouponSid() + "]已发放完";
					continue;
				}

				if ((stock.getGiveBeginDate() > 0 && stock.getGiveBeginDate() > getCurrentDate()) ||
						(stock.getGiveEndDate() > 0 && stock.getGiveEndDate() < getCurrentDate())){
					if (!errorInfo.isEmpty()) errorInfo += ", ";
					errorInfo +=  "优惠券[coupon_sid=" + one.getCouponSid() + "]不在发放时间[" +
							stock.getGiveBeginDate() + "-" + stock.getGiveEndDate() + "]内";
					continue;
				}

				if (stock.getLimitAmount() > 0){
					Map<String, Object> mapIn = new HashMap<>();
					mapIn.put("couponSid", one.getCouponSid());
					mapIn.put("userId", couponActivityGiveVO.getUser_id());
					int givedAmount = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectCount", mapIn);
					if (givedAmount + 1 > stock.getLimitAmount()){
						if (!errorInfo.isEmpty()) errorInfo += ", ";
						errorInfo += "优惠券[coupon_sid=" + one.getCouponSid() + "]限制用户只能获取" +
										stock.getLimitAmount() + "张，目前用户已经获取" + givedAmount + "张";
						continue;
					}
				}
				// 更新发放数量
				conn.update(MAPPER_PATH + "CouponStockMapper.incGiveAmount", one);

				company_id = stock.getCompanyId();
				// 用户优惠券表添加一张
				CouponUser couponUser = new CouponUser();
				couponUser.setMycat_flag(ConfigValues.getMycatFlag());
				couponUser.setCouponSid(stock.getCouponSid());
				couponUser.setCompanyId(stock.getCompanyId());
				couponUser.setUseBeginDate(0);
				couponUser.setUseEndDate(0);
				if (stock.getDuration() > 0){
					couponUser.setUseBeginDate(getCurrentDate());
					couponUser.setUseEndDate(getDate(getCurrentDate(), (int)(long)stock.getDuration()));
				} else {
					if (stock.getUseBeginDate() > 0){
						couponUser.setUseBeginDate(stock.getUseBeginDate());
					}
					if (stock.getUseEndDate() > 0) {
						couponUser.setUseBeginDate(stock.getUseBeginDate());
					}
				}

				if (stock.getCouponCode() == null || stock.getCouponCode().isEmpty()){
					do{
						couponUser.setCouponCode(generateRandomString(16));
					}while ((int)conn.selectOne(MAPPER_PATH + "CouponUserMapper.testCouponCode", couponUser) > 0);
				} else {
					couponUser.setCouponCode(stock.getCouponCode());
				}
				couponUser.setUserId(couponActivityGiveVO.getUser_id());
				couponUser.setCouponStatus((byte)0);
				couponUser.setLockKey(" ");
				couponUser.setLockExpireTime((long)0);
				couponUser.setOrderId("");
				couponUser.setOrderPrice((float)0);
				couponUser.setRealDiscount((float)0);
				couponUser.setRealPay((float)0);
				couponUser.setCreateTime(System.currentTimeMillis());
				couponUser.setDeleteTime((long)0);
				couponUser.setRemark("");
				conn.insert(MAPPER_PATH + "CouponUserMapper.insert", couponUser);
				Long lastInsertId = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectLastInsertId");
				couponUids.add(lastInsertId);
				oneSucceed = true;
			}

			if (!oneSucceed){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, errorInfo, CouponActivityGiveBack.class);
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId(nullToEmpty(couponActivityGiveVO.getExtern_id()));
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid((long)0);
			couponJournal.setBusinessId((long)0);
			couponJournal.setCompanyId(company_id);
			couponJournal.setUserId(couponActivityGiveVO.getUser_id());
			couponJournal.setActivityId(couponActivityGiveVO.getActivity_id());
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_ACTIVITY_GIVE));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());

			couponJournal.setRemark("优惠券活动发放:" + JSONObject.toJSON(couponUids).toString().replace("\\",""));
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			CouponActivityGiveBack back = new CouponActivityGiveBack();
			back.setCoupon_uids(couponUids);
			conn.commit();
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponActivityGiveBack.class);
		}finally{
			conn.close();
		}
	}

	@Override
	public CouponActivityGiveBack couponActivityGiveManage(CouponActivityGiveVO couponActivityGiveVO) {
		return couponActivityGive(couponActivityGiveVO);
	}

	// 优惠券运营发放/积分兑换
	public CouponGiveBack couponGive(CouponGiveVO couponGiveVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponStock in = new CouponStock();
			in.setCouponSid(couponGiveVO.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectForUpdate", in);
			if ( stock == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_sid=" + couponGiveVO.getCoupon_sid() + "]不存在", CouponGiveBack.class);
			}

			Map<String, Object> mapIn1 = new HashMap<String, Object>();
			mapIn1.put("userId", couponGiveVO.getUser_id());
			if ((int)conn.selectOne(MAPPER_PATH + "CouponUserMapper.testUserId", mapIn1) <= 0){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "user_id=" + couponGiveVO.getUser_id() + "不存在", CouponGiveBack.class);
			}

			if (stock.getCouponStockStatus() != 0) {
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST,  "优惠券[coupon_sid=" + couponGiveVO.getCoupon_sid() + "]状态不正确无法发放/兑换", CouponGiveBack.class);
			}

			if (stock.getGiveAmount() + couponGiveVO.getAmount() >= stock.getTotalAmount()) {
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "优惠券[coupon_sid=" + couponGiveVO.getCoupon_sid() + "]可用数量不足", CouponGiveBack.class);
			}

			if ((stock.getGiveBeginDate() > 0 && stock.getGiveBeginDate() > getCurrentDate()) ||
					(stock.getGiveEndDate() > 0 && stock.getGiveEndDate() < getCurrentDate())){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR,
						"优惠券[coupon_sid=" + couponGiveVO.getCoupon_sid() + "]不在发放时间[" +
								stock.getGiveBeginDate() + "-" + stock.getGiveEndDate() + "]内", CouponGiveBack.class);
			}

			if (stock.getLimitAmount() > 0){
				Map<String, Object> mapIn = new HashMap<>();
				mapIn.put("couponSid", couponGiveVO.getCoupon_sid());
				mapIn.put("userId", couponGiveVO.getUser_id());
				int givedAmount = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectCount", mapIn);
				if (givedAmount + couponGiveVO.getAmount() > stock.getLimitAmount()){
					return VOUtil.genErrorResult(COUPON_CONDITION_ERROR,
							"优惠券[coupon_sid=" + couponGiveVO.getCoupon_sid() + "]限制用户只能获取" +
									stock.getLimitAmount() + "张，目前用户已经获取" + givedAmount + "张", CouponGiveBack.class);
				}
			}

			// 增加发放数量
			Map<String , Object> mapIn = new HashMap<String, Object>();
			mapIn.put("couponSid", couponGiveVO.getCoupon_sid());
			mapIn.put("amount", couponGiveVO.getAmount());
			conn.update(MAPPER_PATH + "CouponStockMapper.addGiveAmount", mapIn);

			List<Long> couponUids = new ArrayList<Long>();
			// 用户优惠券表添加多张
			for (int i=0;i<couponGiveVO.getAmount();i++) {
				CouponUser couponUser = new CouponUser();
				couponUser.setMycat_flag(ConfigValues.getMycatFlag());
				couponUser.setCouponSid(stock.getCouponSid());
				couponUser.setCompanyId(stock.getCompanyId());
				if (stock.getCouponCode() == null || stock.getCouponCode().isEmpty()) {
					do {
						couponUser.setCouponCode(generateRandomString(16));
					} while ((int) conn.selectOne(MAPPER_PATH + "CouponUserMapper.testCouponCode", couponUser) > 0);
				} else {
					couponUser.setCouponCode(stock.getCouponCode());
				}
				couponUser.setUserId(couponGiveVO.getUser_id());
				couponUser.setCouponStatus((byte) 0);
				couponUser.setLockKey(" ");
				couponUser.setLockExpireTime((long) 0);
				couponUser.setOrderId("");
				couponUser.setOrderPrice((float) 0);
				couponUser.setRealDiscount((float) 0);
				couponUser.setRealPay((float) 0);
				couponUser.setCreateTime(System.currentTimeMillis());
				couponUser.setDeleteTime((long) 0);

				couponUser.setUseBeginDate(0);
				couponUser.setUseEndDate(0);
				if (stock.getDuration() > 0){
					couponUser.setUseBeginDate(getCurrentDate());
					couponUser.setUseEndDate(getDate(getCurrentDate(), (int)(long)stock.getDuration()));
				} else {
					if (stock.getUseBeginDate() > 0){
						couponUser.setUseBeginDate(stock.getUseBeginDate());
					}
					if (stock.getUseEndDate() > 0) {
						couponUser.setUseBeginDate(stock.getUseBeginDate());
					}
				}
				couponUser.setRemark("");
				conn.insert(MAPPER_PATH + "CouponUserMapper.insert", couponUser);
				Long lastInsertId = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectLastInsertId");
				couponUids.add(lastInsertId);
			}

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId(nullToEmpty(couponGiveVO.getExtern_id()));
			couponJournal.setCouponUid((long)0);
			couponJournal.setCouponSid(stock.getCouponSid());
			couponJournal.setBusinessId(stock.getBusinessId());
			couponJournal.setCompanyId(stock.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_GIVE));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());
			couponJournal.setRemark("优惠券积分兑换/系统发放");
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			CouponGiveBack back = new CouponGiveBack();
			back.setCoupon_uids(couponUids);
			conn.commit();
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponGiveBack.class);
		}finally{
			conn.close();
		}
	}

	@Override
	public CouponGiveBack couponGiveManage(CouponGiveVO couponGiveVO) {
		return couponGive(couponGiveVO);
	}

	// 用户优惠券查询
	public CouponUserQryBack couponUserQry(CouponUserQryVO couponUserQryVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			// 查询前扫描过期优惠券
			updateUserExpired(conn);

			Map<String, Object> mapIn = new HashMap<String, Object>();
			mapIn.put("couponUid", couponUserQryVO.getCoupon_uid());
			mapIn.put("userId", couponUserQryVO.getUser_id());
			mapIn.put("couponSid", couponUserQryVO.getCoupon_sid());
			mapIn.put("companyId", couponUserQryVO.getCompany_id());
			mapIn.put("businessId", couponUserQryVO.getBusiness_id());
			mapIn.put("couponCode", couponUserQryVO.getCoupon_code());
			mapIn.put("couponStatus", couponUserQryVO.getCoupon_status());
			mapIn.put("couponType", couponUserQryVO.getCoupon_type());
			mapIn.put("useBeginDate", couponUserQryVO.getUse_begin_date());
			mapIn.put("useEndDate", couponUserQryVO.getUse_end_date());
			mapIn.put("pageNo", couponUserQryVO.getPage_no());
			mapIn.put("pageSize", couponUserQryVO.getPage_size());

			int count = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectCount", mapIn);
			List<CouponUserQryBean> retList = conn.selectList(MAPPER_PATH + "CouponUserMapper.selectCondition", mapIn);
			CouponUserQryBack back = new CouponUserQryBack();
			back.setCount(count);
			back.setData_list(retList);
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponUserQryBack.class);
		}finally{
			conn.close();
		}
	}

	@Override
	public CouponUserQryBack couponUserQryManage(CouponUserQryVO couponUserQryVO) {
		return couponUserQry(couponUserQryVO);
	}

	// 优惠券使用预览
	public CouponUsePreviewBack couponUsePreview(CouponUsePreviewVO couponUsePreviewVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			Map<String, Object> mapIn = new HashMap<String, Object>();
			mapIn.put("couponUid", couponUsePreviewVO.getCoupon_uid());
			CouponUserQryBean retBean = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectCondition", mapIn);
			if (retBean == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "用户优惠券[coupon_uid=" + couponUsePreviewVO.getCoupon_uid() +"]不存在", CouponUsePreviewBack.class);
			}
			mapIn.put("couponSid", retBean.getCoupon_sid());
			CouponStock stock = conn.selectOne(MAPPER_PATH + "CouponStockMapper.selectByPrimaryKey", mapIn);
			if (stock == null) {
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "库存优惠券[coupon_uid=" + retBean.getCoupon_sid() +"]不存在", CouponUsePreviewBack.class);
			}
			if (stock.getLimitGoods() == 1) {
				mapIn.put("goodsId", couponUsePreviewVO.getGoods_id());
				if ((int) conn.selectOne(MAPPER_PATH + "CouponStockMapper.testLimitId", mapIn) <= 0) {
					return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "用户优惠券[coupon_uid=" + couponUsePreviewVO.getCoupon_uid() + "]不能被此商品[goods_id=" + couponUsePreviewVO.getGoods_id() + "]使用", CouponUsePreviewBack.class);
				}
			}
			if (retBean.getCoupon_status() != 0){
				CouponUser in = new CouponUser();
				in.setCouponUid(couponUsePreviewVO.getCoupon_uid());
				CouponUser couponUser = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectForUpdate", in);
				if (retBean.getCoupon_status() == 1 && couponUser != null && couponUser.getLockExpireTime() < System.currentTimeMillis()){
					CouponUser updateRecord = new CouponUser();
					updateRecord.setCouponUid(couponUsePreviewVO.getCoupon_uid());
					updateRecord.setCouponStatus((byte)0);
					updateRecord.setLockKey("");
					updateRecord.setLockExpireTime((long)0);
					conn.update(MAPPER_PATH + "CouponUserMapper.updateByPrimaryKey", updateRecord);
					conn.commit();
				} else {
					return VOUtil.genErrorResult(COUPON_CONDITION_ERROR,
							"优惠券[coupon_sid=" + couponUsePreviewVO.getCoupon_uid() + "]状态不正确[coupon_status="
									+ retBean.getCoupon_status() + "],无法使用", CouponUsePreviewBack.class);
				}
			}
			if (retBean.getUse_begin_date() > getCurrentDate() ){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR,
						"优惠券[coupon_sid=" + couponUsePreviewVO.getCoupon_uid() + "]不在使用时间[" +
								retBean.getUse_begin_date() + "-" + retBean.getUse_end_date() + "]内", CouponUsePreviewBack.class);
			}
			CouponUser updateRecord = new CouponUser();
			updateRecord.setCouponUid(couponUsePreviewVO.getCoupon_uid());
			if (retBean.getUse_end_date() < getCurrentDate()){
				updateRecord.setCouponStatus((byte)3);
				conn.update(MAPPER_PATH + "CouponUserMapper.updateByPrimaryKey", updateRecord);
				conn.commit();
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR,
						"优惠券[coupon_sid=" + couponUsePreviewVO.getCoupon_uid() + "]已过期", CouponUsePreviewBack.class);
			}
			float realDiscount = 0;
			float realPay = 0;

			if (retBean.getCoupon_type() == 1){//折扣券
				if (retBean.getDiscount_limit() <= 1e-6){
					realPay = couponUsePreviewVO.getOrder_price() * retBean.getDiscount_rate();
				} else {
					realPay = retBean.getDiscount_limit() >= couponUsePreviewVO.getOrder_price() ?
							couponUsePreviewVO.getOrder_price() * retBean.getDiscount_rate() :
							(couponUsePreviewVO.getOrder_price() - retBean.getDiscount_limit()  +
									retBean.getDiscount_limit() * retBean.getDiscount_rate());
				}
				realDiscount = couponUsePreviewVO.getOrder_price() - realPay;
			} else if (retBean.getCoupon_type() == 2){//抵扣券
				realDiscount = retBean.getDiscount_amount();
				realPay = couponUsePreviewVO.getOrder_price() - realDiscount;
			} else if (retBean.getCoupon_type() == 3){//满减券
				if (couponUsePreviewVO.getOrder_price() < retBean.getDiscount_limit()){
					return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "消费金额不满足满减券的使用[order_price="
							+ couponUsePreviewVO.getOrder_price() + ", discount_limit=" + retBean.getDiscount_limit() +"]"
							, CouponUsePreviewBack.class);
				}
				realDiscount = retBean.getDiscount_amount();
				realPay = couponUsePreviewVO.getOrder_price() - realDiscount;
			}


			// 更新优惠券状态为已使用
			updateRecord.setCouponStatus((byte)1);
			updateRecord.setOrderId(couponUsePreviewVO.getOrder_id());
			updateRecord.setOrderPrice(couponUsePreviewVO.getOrder_price());
			updateRecord.setRealDiscount(realDiscount);
			updateRecord.setRealPay(realPay);
			Long timeStamp = System.currentTimeMillis();
			String lockKey = sha256(couponUsePreviewVO.getCoupon_uid() + "|" + timeStamp);
			updateRecord.setLockKey(lockKey);
			updateRecord.setLockExpireTime(timeStamp + COUPON_LOCK_INTERVAL);
			conn.update(MAPPER_PATH + "CouponUserMapper.updateByPrimaryKey", updateRecord);

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId(nullToEmpty(couponUsePreviewVO.getExtern_id()));
			couponJournal.setCouponUid(retBean.getCoupon_uid());
			couponJournal.setCouponSid(retBean.getCoupon_sid());
			couponJournal.setBusinessId(retBean.getBusiness_id());
			couponJournal.setCompanyId(retBean.getCompany_id());
			couponJournal.setUserId(couponUsePreviewVO.getUser_id());
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_USE_PREVIEW));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());
			couponJournal.setRemark("优惠券使用预览");
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			CouponUsePreviewBack back = new CouponUsePreviewBack();
			back.setLock_key(lockKey);
			back.setReal_discount(realDiscount);
			conn.commit();
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponUsePreviewBack.class);
		}finally{
			conn.close();
		}
	}

	// 优惠券使用确认
	public HSBCPSBackVO couponUseConfirm(CouponUseConfirmVO couponUseConfirmVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponUser in = new CouponUser();
			in.setCouponUid(couponUseConfirmVO.getCoupon_uid());
			CouponUser couponUser = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectForUpdate", in);
			if (couponUser == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "用户优惠券[coupon_sid=" + couponUseConfirmVO.getCoupon_uid() +"]不存在", CouponUsePreviewBack.class);
			}
			if (couponUser.getCouponStatus() != 1){
				return VOUtil.genErrorResult(COUPON_NOT_LOCK, "用户优惠券[coupon_sid=" + couponUseConfirmVO.getCoupon_uid() +"]未锁定，请先调用coupon_use_preview接口", CouponUsePreviewBack.class);
			}

			if (!couponUser.getLockKey().equalsIgnoreCase(couponUser.getLockKey())){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "用户优惠券[coupon_sid=" + couponUseConfirmVO.getCoupon_uid() +"]锁定密钥不正确，可能此优惠券正在被其他订单使用", CouponUsePreviewBack.class);
			}

			if (abs(couponUser.getRealPay() - couponUseConfirmVO.getReal_pay()) > 1e-6 ){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "用户优惠券[coupon_sid=" + couponUseConfirmVO.getCoupon_uid() +"]实付金额与预览时计算不一致", CouponUsePreviewBack.class);
			}

			CouponUser updateRecord = new CouponUser();
			updateRecord.setCouponUid(couponUseConfirmVO.getCoupon_uid());
			updateRecord.setCouponStatus((byte)2);
			updateRecord.setDeleteTime(System.currentTimeMillis());
			conn.update(MAPPER_PATH + "CouponUserMapper.updateByPrimaryKey", updateRecord);

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId(nullToEmpty(couponUseConfirmVO.getExtern_id()));
			couponJournal.setCouponUid(couponUser.getCouponUid());
			couponJournal.setCouponSid(couponUser.getCouponSid());
			couponJournal.setBusinessId((long)0);
			couponJournal.setCompanyId(couponUser.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_USE_CONFIRM));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());
			couponJournal.setRemark("优惠券使用确认");
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 优惠券使用取消
	public HSBCPSBackVO couponUseCancel(CouponUseCancelVO couponUseCancelVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			CouponUser in = new CouponUser();
			in.setCouponUid(couponUseCancelVO.getCoupon_uid());
			CouponUser couponUser = conn.selectOne(MAPPER_PATH + "CouponUserMapper.selectForUpdate", in);
			if (couponUser == null){
				return VOUtil.genErrorResult(COUPON_STOCK_NOT_EXIST, "用户优惠券[coupon_uid=" + couponUseCancelVO.getCoupon_uid() +"]不存在", CouponUsePreviewBack.class);
			}
			if (couponUser.getCouponStatus() != 1) {
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR,
						"优惠券[coupon_sid=" + couponUseCancelVO.getCoupon_uid() + "]状态不正确[coupon_status="
								+ couponUser.getCouponStatus() + "],无法取消", HSBCPSBackVO.class);
			}

			if (!couponUser.getLockKey().equalsIgnoreCase(couponUseCancelVO.getLock_key())){
				return VOUtil.genErrorResult(COUPON_CONDITION_ERROR, "用户优惠券[coupon_sid=" + couponUseCancelVO.getCoupon_uid() +"]锁定密钥不正确，可能此优惠券正在被其他订单使用", CouponUsePreviewBack.class);
			}

			CouponUser updateRecord = new CouponUser();
			updateRecord.setCouponUid(couponUseCancelVO.getCoupon_uid());
			updateRecord.setCouponStatus((byte)0);
			updateRecord.setLockKey("");
			updateRecord.setLockExpireTime((long)0);
			conn.update(MAPPER_PATH + "CouponUserMapper.updateByPrimaryKey", updateRecord);

			CouponJournal couponJournal = new CouponJournal();
			couponJournal.setMycat_flag(ConfigValues.getMycatFlag());
			couponJournal.setExternId(nullToEmpty(couponUseCancelVO.getExtern_id()));
			couponJournal.setCouponUid(couponUser.getCouponUid());
			couponJournal.setCouponSid(couponUser.getCouponSid());
			couponJournal.setBusinessId((long)0);
			couponJournal.setCompanyId(couponUser.getCompanyId());
			couponJournal.setUserId((long)0);
			couponJournal.setActivityId((long)0);
			couponJournal.setGoodsId((long)0);
			couponJournal.setFunctionId(Long.parseLong(IFSFunctionIds.IFSLTBCouponFunIds.FUNC_COUPON_USE_CANCEL));
			couponJournal.setSysDate(getCurrentDate());
			couponJournal.setSysTime(getCurrentTime());
			couponJournal.setRemark("优惠券使用取消");
			conn.insert(MAPPER_PATH + "CouponJournalMapper.insert", couponJournal);

			conn.commit();
			return VOUtil.genSuccessBackVo();
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), HSBCPSBackVO.class);
		}finally{
			conn.close();
		}
	}

	// 优惠券流水查询
	public CouponJournalQryBack couponJournalQry(CouponJournalQryVO couponJournalQryVO){
		SqlSession conn = sqlSessionFactory.openSession();
		try{
			Map<String, Object> mapIn = new HashMap<String, Object>();
			mapIn.put("couponJournalId", couponJournalQryVO.getCoupon_journal_id());
			mapIn.put("externId", emptyToNull(couponJournalQryVO.getExtern_id()));
			mapIn.put("couponUid", couponJournalQryVO.getCoupon_uid());
			mapIn.put("couponSid", couponJournalQryVO.getCoupon_sid());
			mapIn.put("businessId", couponJournalQryVO.getBusiness_id());
			mapIn.put("companyId", emptyToNull(couponJournalQryVO.getCompany_id()));
			mapIn.put("userId", couponJournalQryVO.getUser_id());
			mapIn.put("activityId", couponJournalQryVO.getActivity_id());
			mapIn.put("goodsId", couponJournalQryVO.getGoods_id());
			mapIn.put("functionId", couponJournalQryVO.getFunction_id());
			mapIn.put("beginDate", couponJournalQryVO.getBegin_date());
			mapIn.put("endDate", couponJournalQryVO.getEnd_date());
			mapIn.put("beginTime", couponJournalQryVO.getBegin_time());
			mapIn.put("endTime", couponJournalQryVO.getEnd_time());

			int count = conn.selectOne(MAPPER_PATH + "CouponJournalMapper.selectCount", mapIn);
			List<CouponJournalQryBean> retList = conn.selectList(MAPPER_PATH + "CouponJournalMapper.selectCondition", mapIn);
			CouponJournalQryBack back = new CouponJournalQryBack();
			back.setCount(count);
			back.setData_list(retList);
			return VOUtil.setSuccessResult(back);
		}catch(Exception e){
			return VOUtil.genErrorResult(DATABASE_OPERATE_EORR, "数据库操作失败:" + e.getMessage(), CouponJournalQryBack.class);
		}finally{
			conn.close();
		}
	}

	@Override
	public CouponJournalQryBack couponJournalQryManage(CouponJournalQryVO couponJournalQryVO) {
		return couponJournalQry(couponJournalQryVO);
	}

}
